package com.back.demo.controller;

import com.back.demo.common.CommonResult;
import com.back.demo.controller.myVO.*;
import com.back.demo.service.BasicService;
import com.back.demo.util.JwtTokenUtil;
import com.back.demo.mapper.myDO.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "基础功能")
@RestController
@RequestMapping("/basic")
public class BasicController {

    @Autowired
    private BasicService basicService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;



    @ApiOperation("登录接口")
    @PostMapping("/login")
    public CommonResult<?> login(@RequestBody LoginReqVO loginUser) {
        String username = loginUser.getUsername();

        // 查询用户
        User user = basicService.findPasswordByUsername(username);
        if (user == null) {
            return CommonResult.error(50007, "登录失败，用户不存在");
        }
//        System.out.println(loginUser.getPassword());
//        System.out.println(user.getPassword());
        if (!loginUser.getPassword().equals(user.getPassword())) {
            return CommonResult.error(50007, "登录失败，密码不正确");
        }

        // 生成访问令牌和刷新令牌
        String accessToken = jwtTokenUtil.generateAccessToken(username);
        String refreshToken = jwtTokenUtil.generateRefreshToken(username);
        LoginResVO tokenRes = new LoginResVO(accessToken, refreshToken);

        return CommonResult.success(tokenRes);
    }

    @PostMapping("/register")
    public CommonResult<?> register(@RequestBody RegisterReqVO registerUser) {
        User user = basicService.findNameByUsername(registerUser.getUsername());

        if (user != null) {
            return CommonResult.error(50003, "用户已存在");
        }

        user = new User(registerUser.getUsername(), registerUser.getPassword()
                , registerUser.getName(), registerUser.getPhone()
                , registerUser.getEmail());
        try {
            // 将用户信息保存到数据库
            basicService.register(user);
        } catch (Exception e) {
            // 处理插入失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "注册失败");
        }
        return CommonResult.success("注册成功");
    }

    @GetMapping("/get")
    public CommonResult<?> getUserProfile(@RequestHeader("Authorization") String authHeader) {
        // 解析Authorization请求头中的JWT令牌 Bearer access_token
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        User user = basicService.findInformationByUsername(username);
        return CommonResult.success(user);
    }

    @PostMapping("/password")
    public CommonResult<?> changePassword(@RequestHeader("Authorization") String authHeader, @RequestBody ChangePasswordReqVO body) {
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        User user = basicService.findNameByUsername(username);

        if (user == null) {
            return CommonResult.error(50003, "用户不存在，修改密码失败");
        }

        if (!user.getPassword().equals(body.getOldPassword())) {
            return CommonResult.error(50003, "旧密码错误");
        }

        try {
            // 执行修改密码的操作
            basicService.changePassword(username, body.getNewPassword());
        } catch (Exception e) {
            // 处理修改失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "修改密码失败");
        }
        return CommonResult.success("修改密码成功");
    }

    @PostMapping("/information")
    public CommonResult<?> changeInformation(@RequestHeader("Authorization") String authHeader, @RequestBody ChangeInformationReqVO body) {
        String token = authHeader.substring(7);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        User user = basicService.findNameByUsername(username);

        if (user == null) {
            return CommonResult.error(50003, "用户不存在，修改个人信息失败");
        }

        try {
            // 执行修改个人信息的操作
            basicService.changeInformation(username, body.getPhone(), body.getEmail());
        } catch (Exception e) {
            // 处理修改失败的情况
            System.out.println(e.toString());
            return CommonResult.error(50003, "修改个人信息失败");
        }
        return CommonResult.success("修改个人信息成功");
    }


}